<script lang="ts" setup>
import { reactive, ref } from "vue"
import { createAmountRangeApi, updateAmountRangeApi, getBankssearchApi } from "@/api/calculator"
import { type FormInstance, type FormRules, ElMessage } from "element-plus"

interface Emits {
  (e: "success"): void
}

const emit = defineEmits<Emits>()

const formRef = ref<FormInstance | null>(null)
const loading = ref<boolean>(false)
const visible = ref<boolean>(false)
const editData = ref<any>(undefined)

const formData = reactive({
  name: "",
  min_amount: "",
  max_amount: "",
  description: "",
  bank_id: "",
  bank_name: "",
  type_id: 1 // 添加默认类型ID
})

const formRules: FormRules = reactive({
  name: [{ required: true, trigger: "blur", message: "请输入区间名称" }],
  min_amount: [{ required: true, trigger: "blur", message: "请输入最小金额" }],
  max_amount: [{ required: true, trigger: "blur", message: "请输入最大金额" }],
  bank_name: [{ required: true, trigger: "blur", message: "请选择银行" }]
})

// 银行搜索相关
const querySearchAsync = (queryString: string, cb: (suggestions: any[]) => void) => {
  if (queryString) {
    getBankssearchApi({ bank_name: queryString })
      .then((res: any) => {
        const suggestions = res.data.data.map((bank: any) => ({
          value: bank.bank_name,
          id: bank.bank_id,
          ...bank
        }))
        cb(suggestions)
      })
      .catch(() => {
        cb([])
      })
  } else {
    cb([])
  }
}

const handleBankSelect = (item: any) => {
  console.log(item)
  formData.bank_id = item.id
  formData.bank_name = item.value
}

// 重置表单
const resetForm = () => {
  formData.name = ""
  formData.min_amount = ""
  formData.max_amount = ""
  formData.description = ""
  formData.bank_id = ""
  formData.bank_name = ""
  formData.type_id = 1
  formRef.value?.resetFields()
}

// 打开对话框 - 新增
const openAdd = () => {
  editData.value = undefined
  resetForm()
  visible.value = true
}

// 打开对话框 - 编辑
const openEdit = (data: any) => {
  editData.value = data
  formData.name = data.name || ""
  formData.min_amount = data.min_amount || ""
  formData.max_amount = data.max_amount || ""
  formData.description = data.description || ""
  formData.bank_id = data.bank_id || ""
  formData.bank_name = data.bank_name || ""
  formData.type_id = data.type_id || 1
  visible.value = true
}

// 提交表单
const handleSubmit = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      loading.value = true
      const submitData = {
        name: formData.name,
        type_id: formData.type_id,
        min_amount: formData.min_amount,
        max_amount: formData.max_amount,
        description: formData.description,
        bank_id: formData.bank_id
      }

      const apiCall = editData.value
        ? updateAmountRangeApi({ range_id: editData.value.range_id, ...submitData })
        : createAmountRangeApi(submitData)

      apiCall
        .then(() => {
          ElMessage.success(editData.value ? "修改成功" : "新增成功")
          emit("success")
          handleClose()
        })
        .finally(() => {
          loading.value = false
        })
    }
  })
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  resetForm()
}

// 暴露方法给父组件调用
defineExpose({
  openAdd,
  openEdit
})
</script>

<template>
  <el-dialog v-model="visible" :title="editData ? '修改金额区间' : '新增金额区间'" width="500px" @close="handleClose">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      label-position="left"
      v-loading="loading"
    >
      <el-form-item prop="name" label="区间名称">
        <el-input v-model="formData.name" placeholder="请输入区间名称" />
      </el-form-item>
      <el-form-item prop="bank_name" label="所属银行">
        <el-autocomplete
          v-model="formData.bank_name"
          :fetch-suggestions="querySearchAsync"
          placeholder="请输入银行名称搜索"
          @select="handleBankSelect"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item prop="min_amount" label="最小金额">
        <el-input v-model="formData.min_amount" placeholder="请输入最小金额" type="number" />
      </el-form-item>
      <el-form-item prop="max_amount" label="最大金额">
        <el-input v-model="formData.max_amount" placeholder="请输入最大金额" type="number" />
      </el-form-item>
      <el-form-item prop="description" label="描述">
        <el-input v-model="formData.description" placeholder="请输入描述" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">确认</el-button>
    </template>
  </el-dialog>
</template>
